package com.wh.wisdomsite.xbox.core.config.spring;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import java.util.List;

/**
 *
 * @Package com.wh.wisdomsite.xbox.core.config.spring
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
public class ListenerBeanDefinitionParser implements BeanDefinitionParser {


    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        Object source = parserContext.extractSource(element);
        CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
        parserContext.pushContainingComponent(compDefinition);
        List<Element> listeners = DomUtils.getChildElementsByTagName(element, new String[]{"bean", "ref"});
        for (Element listener : listeners) {
            RootBeanDefinition listenerHolder = new RootBeanDefinition(XboxListenerHolder.class);
            listenerHolder.setSource(source);
            listenerHolder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

            Object listenerBean = parserContext.getDelegate().parsePropertySubElement(listener, null);
            listenerHolder.getConstructorArgumentValues().addIndexedArgumentValue(0, listenerBean);

            String beanName = parserContext.getReaderContext().registerWithGeneratedName(listenerHolder);
            parserContext.registerComponent(new BeanComponentDefinition(listenerHolder, beanName));
        }
        parserContext.popAndRegisterContainingComponent();
        return null;
    }


}
